import { loadStripe, Stripe, StripeElements } from '@stripe/stripe-js';

// Replace with your Stripe publishable key
// @ts-expect-error - Vite env variable
const STRIPE_PUBLISHABLE_KEY = import.meta.env?.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_test_YOUR_KEY_HERE';

let stripePromise: Promise<Stripe | null>;

/**
 * Get Stripe instance
 */
export const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY);
  }
  return stripePromise;
};

/**
 * Create Payment Intent for cart checkout
 */
export const createPaymentIntent = async (amount: number, currency: string = 'usd') => {
  try {
    // Call backend API endpoint
    const response = await fetch('http://localhost:3001/api/payment/create-intent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: Math.round(amount * 100), // Convert to cents
        currency,
      }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || 'Failed to create payment intent');
    }

    const data = await response.json();
    return {
      success: true,
      clientSecret: data.clientSecret,
      paymentIntentId: data.paymentIntentId,
    };
  } catch (error) {
    console.error('Create payment intent failed:', error);
    return { success: false, error };
  }
};

/**
 * Confirm Payment Intent
 */
export const confirmPayment = async (
  stripe: Stripe,
  elements: StripeElements,
  clientSecret: string,
  billingDetails: {
    name: string;
    email: string;
    address?: {
      line1: string;
      city?: string;
      postal_code?: string;
      country?: string;
    };
  }
) => {
  try {
    // Submit the form to validate before confirming payment
    const { error: submitError } = await elements.submit();
    
    if (submitError) {
      return { success: false, error: submitError.message };
    }

    const { error, paymentIntent } = await stripe.confirmPayment({
      elements,
      clientSecret,
      confirmParams: {
        payment_method_data: {
          billing_details: billingDetails,
        },
        return_url: window.location.origin + '/cart/success',
      },
      redirect: 'if_required',
    });

    if (error) {
      return { success: false, error: error.message };
    }

    return {
      success: true,
      paymentIntent,
    };
  } catch (error) {
    console.error('Confirm payment failed:', error);
    return { success: false, error };
  }
};

/**
 * Process completed order
 */
export const processOrder = async (paymentIntentId: string, orderDetails: any) => {
  try {
    // TODO: Replace with your actual API endpoint
    const response = await fetch('/api/process-order', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        paymentIntentId,
        orderDetails,
      }),
    });

    if (!response.ok) {
      throw new Error('Failed to process order');
    }

    const data = await response.json();
    return {
      success: true,
      order: data.order,
    };
  } catch (error) {
    console.error('Process order failed:', error);
    return { success: false, error };
  }
};

export const stripeService = {
  getStripe,
  createPaymentIntent,
  confirmPayment,
  processOrder,
};
